package com.rizzo.analytics.services.security;

import com.google.common.collect.Lists;
import com.rizzo.analytics.domain.account.Account;
import com.rizzo.analytics.services.repo.AccountRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

public class AccountUserDetailsService implements UserDetailsService {

    private AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountRepository.findByUsername(username);
        if (account != null) {
            Set<String> roles = StringUtils.commaDelimitedListToSet(account.getRoles());
            List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
            for (String role : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role));
            }
            return new User(account.getUsername(), account.getPassword(),
                    !account.isDisabled(), !account.isExpired(), true, !account.isLocked(),
                    grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("User: " + username + "is unknown!");
        }
    }

    public void setAccountRepository(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }
}
